package com.abc.ollama.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.util.StringUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

@Slf4j
public class WordUtil {

    private static final Integer RANGE_SIZE = 800;
    private static final Integer OVERLAPPING_SIZE = 50;
    private static final List<Character> END_CHARS = new ArrayList<>(Arrays.asList(
            '.', ',', '!', '\n', '?', ';', ':', '。', '，', '！', '？', '；', '：'
    ));

    public static String readFile(String filePath) throws IOException {
        StringBuilder content = new StringBuilder();
        try {
            FileInputStream fis = new FileInputStream(filePath);
            XWPFDocument document = new XWPFDocument(fis);
            // 遍历文档中的所有元素（段落和表格）
            List<IBodyElement> bodyElements = document.getBodyElements();
            for (IBodyElement bodyElement : bodyElements) {
                if (bodyElement instanceof XWPFParagraph paragraph) {
                    content.append(paragraph.getText());
                } else if (bodyElement instanceof XWPFTable) {
                    content.append(((XWPFTable) bodyElement).getText());
                }
            }
            fis.close();
        } catch (IOException e) {
            log.error("Error reading file: {}", e.getMessage());
        }
        return content.toString();
    }

    public static List<String> split(String sentence) {
        List<String> result = new ArrayList<>();
        Map<Integer, Boolean> isCome = new HashMap<>();
        StringBuilder tempStr = new StringBuilder();

        for (int i = 0, j = 0; i < sentence.length(); i++) {
            char word = sentence.charAt(i);
            if (i - j >= OVERLAPPING_SIZE) {
                j++;
            }
            if (i < RANGE_SIZE || i % RANGE_SIZE != 0 || isCome.containsKey(i)) {
                tempStr.append(word);
                continue;
            }

            isCome.put(i, true);
            tempStr.append(word);
            i++;

            while (i < sentence.length() && !END_CHARS.contains(word)) {
                word = sentence.charAt(i);
                tempStr.append(word);
                i++;
            }

            result.add(tempStr.toString().trim());
            tempStr = new StringBuilder();

            if (i != sentence.length() - 1) {
                char tempWord = sentence.charAt(j);
                while (j >= 0 && !END_CHARS.contains(tempWord)) {
                    tempWord = sentence.charAt(j);
                    j--;
                }
                if (j >= 0) {
                    j++;
                }
                i = j;
                j++;
            }
        }
        if (!StringUtils.isEmpty(tempStr)) {
            result.add(tempStr.toString());
        }

        return result;
    }
}
